#! usr/bin/python3
# coding=utf-8
# @Time: 2025/9/20 
# @Author: GaoSheng
from inspect import Parameter, signature


def join_urls(root, *args):
    """拼接url

    :param root: 根路径
    :param args:
    :return:
    """
    urls = []
    if root.endswith(r"\/"):
        root = root[:-2]
    elif root.endswith("/"):
        root = root[:-1]
    urls.append(root)

    for path in args:
        if path is None or path.strip() == "":
            continue

        if path.startswith(r"\/"):
            path = path[2:]
        elif path.startswith("/"):
            path = path[1:]
        urls.append(path)
    return "/".join(urls)


def merge_dicts(d1, d2):
    """合并两个dict对象,如果子节点也是dict,同样会被合并"""
    if d1 is None:
        return d2
    if d2 is None:
        return d1
    common_keys = set(d1.keys()) & set(d2.keys())
    for k in common_keys:
        if isinstance(d1[k], dict) and isinstance(d2[k], dict):
            d2[k] = merge_dicts(d1[k], d2[k])
    d1.update(d2)
    return d1


def smart_payload(func):
    """自动组装payload"""

    def _wrapper(*args, **kwargs):
        func(*args, **kwargs)  # to raise TypeError

        parameters = signature(func).parameters
        arguments = list(parameters.keys())
        payload = {parameter.name: parameter.default for _, parameter in parameters.items() if parameter.default
                   is not Parameter.empty and parameter.name != "self"}
        if arguments[0] == "self":
            arguments.pop(0)
            args = args[1:]

        if args:
            for index, val in enumerate(args):
                arg_name = arguments[index]
                payload[arg_name] = val
        payload.update(kwargs)
        return payload

    return _wrapper


def set_or_update_node(parent: dict, key: str, d: dict):
    if isinstance(parent.get(key, None), dict):
        parent[key].update(d)
    else:
        parent[key] = d
